5

Say I have some command that outputs a bunch of strings. The output from this command could look something like:

... foo bar blargh ... 

Say I have some set string

myString$Blah 

I want to insert each of the strings where the $ is in the output of the command such that I end up with a file that looks like this:

... myStringfooBlah myStringbarBlah myStringblarghBlah ... 

What is the easiest way to accomplish this? (Awk and sed preferred)

3 Answers 3

13

You don't even need sed or awk.

xargs can do this: with: -L1 -I '$' echo 'myString$Blah'

$ cat x.list foo bar blargh $ cat x.list | tr '\n' '\0' | xargs -0 -L1 -I '$' echo 'myString$Blah' myStringfooBlah myStringbarBlah myStringblarghBlah 
1

You can do this completely in the shell (bash, at least) without too much trouble. Here's a script that does that:

#!/bin/bash pattern="$1" input_file="$2" output_file="$3" saved_IFS="$IFS" IFS=$'\n' # Store each line of the input file into an array named 'lines'. lines=($(< $input_file)) IFS="$saved_IFS" # Truncate output file, if any. cat /dev/null > $output_file # Substitute each line into the pattern, and write to output file. for ln in "${lines[@]}" do echo ${pattern/$/$ln} >> $output_file done 

Supposing this script is called script, and you have a file called in.txt with one string per line, then running script in.txt out.txt would give you the desired output in out.txt.

1

Assuming you can use the format string myString&Blah, with an ampersand instead of the dollar sign, pipe your output into this:

sed "s/.*/$format/" 

This works because the & is used as an "insert match here" operator in the replacement string. The regex matches the entire line, so it will insert the whole line at the &.

It is important to use the double quotes to allow expansion of the format string.

If you really need to use the ampersand, use this:

sed "s/.*/$(echo "$format" | tr '$' '&')/" 

The quotes around $format are important if you have whitespace in the string.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.