I have a string of the form:
file1.txt file2.txt ... filen.txt
I do not know how many files there are or whether they will all be .txt files. I do, however, know that they will be separated by spaces.
My goal is to change the string so that the file names are in the appropriate directory. My desired output is:
$1/file1.txt $1/file2.txt ... $1/filen.txt
I have tried using sed and cannot figure how to make this work. I am using sh.
ctsgnb
2
echo "file1.txt file2.txt ... filen.txt" | sed 's/\([^ ][^ ]*\)/\$1\1/g'
1 Like
kurumi
4
$ echo "file1.txt file2.txt filen.txt" | ruby -e 'puts gets.split.map{|x|x="$1/"+x}.join(" ")'
$1/file1.txt $1/file2.txt $1/filen.txt
Assuming, like the solutions above, that you want a literal "$1" prepended to each word (perhaps for future evaluation):
printf '$1/%s ' $str
... or if you want the actual value of $1 subsituted into the output ...
for f in $str; do
printf '%s ' "$1/$f"
done
I think alister's is the most elegant, though it leaves str open to wildcard expansion by the shell if you are using any.
Using sed:
sed 's|[^ ][^ ]*|$1/&|g'
similar to ctsgnb's suggestion
2 Likes
Good point regarding filename expansion, Scrutinizer. Thanks for mentioning it.