0

I have an input file named test.txt like this:

Homo sapiens
Mus musculus
Rat rattus rattus

I want to use a for loop here and loop through each line. Some thing like this:

for i in "`cat test.txt`"
do
        fn=store_name
        do something else > ${fn}.txt
done

Since each line has a space between names I used double quotes in cat test.txt. I want to make a variable fn which attaches _ between these names of the lines so my fn becomes Homo_sapiens and Mus_musculus and if I have Rat rattus rates it becomes Rat_rattus_rattus

How can I achieve this?

slm
  • 369,824
user3138373
  • 2,559

5 Answers5

5

Use tr to transliterate a space to an underscore:

while read line
do
    echo ${line} | tr -s " " "_"
done < test.txt

Homo_sapiens Mus_musculus Rat_rattus_rattus

JRFerguson
  • 14,740
4

Using awk:

awk '{OFS="_";}{$1=$1; print}' test.txt

Using a loop:

while read -r line; do 
  line=${line// /_} 
  command using "$line"
done<test.txt
jesse_b
  • 37,005
2

I'd use sed and read its output with a loop:

sed 's/[[:space:]]\+/_/g' test.txt | while IFS= read -r line; do 
    process "$line" however
done > some.output.file
glenn jackman
  • 85,964
0

Here's a quick for loop that uses sed to get it done:

for file in $(sed "s/ /_/g" test.txt); do echo "test" > $file; done

Just replace the echo command with whatever it is you want to do.

I use commands like this all the time though out the day.

-1

Someone gave an answer with tr and someone else gave one with awk, now here's how to do it with sed:

for i in "`cat test.txt`"
do
    fn="$(echo "$i" |sed -e 's/ /_/g')"
    'do something else' > $fn.txt
done