1

I'm trying to pipe multiple lines into a text file while manipulating the string that is being piped according to a sequence

cmd="My string 00"

for i in $(seq -f "%02g" 00 05); \
  do \
  echo $(echo $cmd | sed -e 's|00|$(echo $i)|g') >> outfile.txt ;  \
done

doesn't work. The output should look like this:

My string 00  
My string 01  
My string 02  
My string 03  
My string 04  
My string 05  

but the output is:

My string $(echo $i)
My string $(echo $i)
My string $(echo $i)
My string $(echo $i)
My string $(echo $i)
My string $(echo $i)
mcExchange
  • 3,088

2 Answers2

2

You can do it all with printf and brace expansion:

$ printf 'My string %02d\n' {0..5} > outfile.txt

$ cat outfile.txt 
My string 00
My string 01
My string 02
My string 03
My string 04
My string 05

If for some reason you must generate the input sequence with more padding than you really want, printf will reformat it for you:

$ printf 'My string %02d\n' $(seq -f "%05g" 00 05)
My string 00
My string 01
My string 02
My string 03
My string 04
My string 05
steeldriver
  • 136,215
  • 21
  • 243
  • 336
  • I cannot hard code the string because it is much more complicated as shown above. I assume printf cannot print variables (like $cmd)? – mcExchange Jul 22 '18 at 04:48
  • @mcExchange you can expand variables within the printf format string provided it is soft-quoted e.g. cmd='My string'; printf "$cmd %02d\n" {0..5} however you need to beware of anything in $cmd that might be interpreted as a format character. Regardless, it sounds like you have an XY problem – steeldriver Jul 22 '18 at 12:30
2
for i in {00000..00005}; do echo "${i/???/My string }"; done >> outfile.txt

Output to outfile.txt:

My string 00
My string 01
My string 02
My string 03
My string 04
My string 05
Cyrus
  • 5,554
  • Can you eplain the '???' part? Why is the order of i and the string inverted? Would this also work if the string was encoded in a variable ($cmd)? – mcExchange Jul 22 '18 at 04:53
  • This is part of bash's Parameter Expansion. echo "$i" or echo "${i}" outputs content of variable i. echo "${i/???/My string }" replaces in output first three characters with your string. A variable with your string is here possible, too. – Cyrus Jul 22 '18 at 05:58