2

For the life of me, I cannot find out how to do this very simple procedure. I want to:

  1. read a file, which consists only of number on each line
  2. append characters before and after the number in the file.

For example, in the contents of the file:

1
2
3

would turn into:

file1.txt
file2.txt
file3.txt

I've tried this:

sed 's/[0-9]+/{file&.txt}/' file_name.txt

but nothing happened. I see snippets online that say use {0} or {/1} but I am having a hard time finding an explanation of what this means.

The end goal of this is to have xargs copy all the filenames in this text to another directory. I am sure there is probably another way to accomplish this without the text file I am doing here. If anyone has a simpler answer to that end goal, that would be nice to hear, although I also want to figure out how to use sed! Thanks.

3 Answers 3

6

Yes, this does work:

$cat file
1
2
3
$sed 's/.*/File&.txt/' file
File1.txt
File2.txt
File3.txt
Sign up to request clarification or add additional context in comments.

Comments

3

In sed, + is not a special character, and literally means the + character. You need to escape it with backslash:

sed 's/[0-9]\+/file&.txt/' file_name.txt

Alternatively you can use the -r option, which adds several special characters (including +):

sed -r 's/[0-9]+/file&.txt/' file_name.txt

2 Comments

The -r switch in GNU sed adds nothing more than "syntactic sugar" in that it removes the need to prepend a backslash before the metacharacters ()+?|
Thanks; I chose this answer b/c it more directly addressed the question.
1

Not sure why you need sed for your end goal (or xargs for that matter). You can simply do:

while read -r name; do 
    cp "File${name}.txt" /path/to/copy
done < file_name.txt

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.