Renaming in Unix/Shell Script

March 1, 2009 at 07:45:25
Specs: Windows XP

I am extracting a line from unix and redirecting the output to a new file. I want to have the new file name as the line extracted from the old file.

For eg:
Command:sed -n 2p test1

I want to have new file name as 12and 26.

can someone one help me on this?

See More: Renaming in Unix/Shell Script

Report •

March 1, 2009 at 10:23:25
I'm interpreting your requirement is to print out 2nd line of the test1 file and create another file with that same name and contents.

The easiest and most straightforward way is to send the output of the sed command to a temporary file, mytest in this case, read the contents of the temporary file, and mv the temporary file to the contents.

That is what this korn shell script does:


# create a file from the 2nd line of file test1
# which has the same contents of the 2nd line:

sed -n 2p test1 > ./mytest
mv mytest $(< mytest)
# end script.

This is another one-liner method:

sed -n 2p test1 |xargs -I {} ksh -c "echo {} > {}"

The output of the sed command is piped to xargs. The xargs -I switch allows replacing the {} with the outpuf of the sed command. I spawn another korn shell and execute an echo command. Effectively this command redirects the string to a filename of the same name:

echo "12and26" > 12and26

Which is best? The first is easiest to undersand and probably more efficient as the 2nd spawns a second shell.

The second method is a one-liner and doesn't create any temporary files.

Report •

March 2, 2009 at 19:16:21
Hi Nails,

Great.. I am ok with the first method.. Thanks a lot.

Report •

Related Solutions

Ask Question