Shreyas Athreya
Shreyas Athreya

Reputation: 113

How to ignore white spaces in awk command

I have a file user_list.txt which has a table of 4 fields separated by ",". For eg,

hi,hello,good morning,bye.

I'm using the below command to extract the third column field.

output=$(awk 'BEGIN { FS = "," } ; { print $3 }' user_list.txt) 

When i try to check the contents of the output variable.,

echo ${output[0]} --> good
echo ${output[1]} --> morning

I want it as a string echo ${output[0]} --> good morning, but since whitespace is the default separator, the string is being split.

Please help.

Upvotes: 0

Views: 8509

Answers (3)

R. Kumar
R. Kumar

Reputation: 109

This can be achieved with the below command. Considering user_list.txt as input file.

awk '{split($0,a,","); print a[3]}' user_list.txt

Upvotes: 0

grail
grail

Reputation: 930

As usual, when you provide a small portion of a much bigger picture it is difficult to answer correctly. It appears you want to do something in bash with values from the third column, so what is wrong with a simple loop:

while IFS=, read -r _ _ item _
do
  <do stuff with $item here>
done<user_list.txt

Of course I could be wrong as the question is poorly devised and makes it hard to render an actual answer

Upvotes: 0

glenn jackman
glenn jackman

Reputation: 247192

In bash, the command to read lines of input into an array is mapfile

mapfile -t output < <(awk -F, '{print $3}' user_list.txt) 

for element in "${output[@]}"    # <= the quotes are crucial here
do
    echo "have: $element"
done

If your input file is just a single line then use cut

output=$(cut -f, -d3 user_list.txt)
echo "have: $output"

Upvotes: 1

Related Questions