7

I have a list of words in lines:

aaaa bbbb ccc dddd
eee fff ggg hhh
iii jjj kkk

I want each word in a separate line:

aaaa
bbbb
ccc
dddd
eee
fff
ggg
hhh
iii
jjj
kkk

How to do that in bash with least number of characters? Without awk preferably.

haael
  • 972
  • 2
  • 10
  • 22

1 Answers1

22

With pure bash:

while IFS=" " read -r -a line
do
    printf "%s\n" "${line[@]}"
done < file

See:

$ while IFS=" " read -r -a line; do printf "%s\n" "${line[@]}"; done < file
aaaa
bbbb
ccc
dddd
eee
fff
ggg
hhh
iii
jjj
kkk

With xargs:

xargs -n 1 < file

With awk:

awk '{for(i=1;i<=NF;i++) print $i}' file

or

awk -v OFS="\n" '$1=$1' file

With GNU sed:

sed 's/ /\n/g' file

With OS sed:

sed $'s/ /\\\n/g' file

With cut:

cut -d' ' --output-delimiter=$'\n' -f1- file

With grep:

grep -o '[^ ]\+' file

or

grep -Po '[^\s]+' file
fedorqui
  • 275,237
  • 103
  • 548
  • 598
  • 1
    Note that the xargs answer will not print any echo flags for example if the file contained `-e/E` or `-n` it will interpret that as an argument to the default echo for xargs. – 123 Apr 18 '16 at 08:56
  • `sed` example doesn't work for me, at least on MacOS. This worked instead `sed -e $'s/,/\\\n/g'` (found here: https://stackoverflow.com/a/18410122/4358405) – TMG Jan 28 '21 at 08:18
  • 1
    @TMG yes! In fact you don't need `-e`. Thanks for the info, I have updated my answer with it. – fedorqui Jan 28 '21 at 08:37
  • Why is the dollar sign necessary in the `--output-delimiter`? What does it do there? – Asclepius Jan 05 '22 at 04:28
  • @Asclepius because if we used `--output-delimiter='\n'` alone it will write a literal string "\n" instead of a new line. The dollar in `$'\n'` is used to tell the command to not treat the string literally. – fedorqui Jan 05 '22 at 07:20