1

I am not a Linux scripting expert and I have exhausted my knowledge on this matter. Here is my situation.

I have a list of states passed as a command line argument to a shell script ( e.g "AL,AK,AS,AZ,AR,CA..." ). The Shell script needs to extract each of the state code and write it to a file ( states.txt) , with each state in one line. See below

AL
AK
AS
AZ
AR
CA
..
..

How can this be achieved using a linux shell script.

Thanks in advance.

4 Answers 4

5

Use tr:

echo "AL,AK,AS,AZ,AR,CA" | tr ',' '\n' > states.txt
Sign up to request clarification or add additional context in comments.

Comments

3
echo "AL,AK,AS,AZ,AR,CA" | awk -F, '{for (i = 1; i <= NF; i++) print $i}';

Comments

1

Naive solution:

echo "AL,AK,AS,AZ,AR,CA" | sed 's/,/\n/g'

Comments

-1

I think awk is the simplest solution, but you could try using cut in a loop. Sample script (outputs to stdout, but you can just redirect it):

#!/bin/bash

# Check for input
if (( ${#1} == 0 )); then
  echo No input data supplied
  exit
fi

# Initialise first input
i=$1

# While $i still contains commas
while { echo $i| grep , > /dev/null; }; do
  # Get first item of $i
  j=`echo $i | cut -d ',' -f '1'`

  # Shift off the first item of $i
  i=`echo $i | cut --complement -d ',' -f '1'`

  echo $j
done

# Display the last item
echo $i

Then you can just run it as ./script.sh "AL,AK,AS,AZ,AR,CA" > states.txt (assuming you save it as script.sh in the local directory and give it execute permission)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.