LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   how to append a file using sed command (https://www.linuxquestions.org/questions/linux-newbie-8/how-to-append-a-file-using-sed-command-931485/)

radhikamody 02-27-2012 12:51 AM

how to append a file using sed command
 
i have this file
test

[z_jigneshb.WF:DS_aftab.ST:s_m_EDW_F_SOP_DMND_FCST_DTL_DS]
$$INPUT_FILE_DATE=000000
$$PFFLAG=0

i am writing a script to change the value for the date and flag which it gets from a file in the same directory.
the name of the file is
DS_P_201202

i have the code working but when i redirect it to the test file, it becomes a blank file

Code:

FILE_NAME=$(ls -tr DS_*|head -1)

DATEMONTH=$(echo $FILE_NAME | cut -d "_" -f3)
DATEMONTH=$(echo $DATEMONTH | cut -d "." -f1)
FLAG=$(echo $FILE_NAME | cut -d "_" -f2)
 
sed '/^\$\$INPUT_FILE_DATE=/s/[0-9]\{6\}/'$DATEMONTH'/' test>test
sed '/^\$\$PFFLAG=/s/.$/'$FLAG'/i test>test


Dark_Helmet 02-27-2012 01:54 AM

Quote:

Code:

sed '/^\$\$INPUT_FILE_DATE=/s/[0-9]\{6\}/'$DATEMONTH'/' test>test
sed '/^\$\$PFFLAG=/s/.$/'$FLAG'/i test>test


You cannot read from a file and redirect output to that same file in a single command.

The shell output redirection operator (>) will truncate/erase the file prior to the command being executed. Because the file has been truncated, there is no data for the sed command to read.

You have two options:

1. Use the sed '-i' option to modify the file in-place. As in:
Code:

sed -i '/^\$\$INPUT_FILE_DATE=/s/[0-9]\{6\}/'$DATEMONTH'/' test
sed -i '/^\$\$PFFLAG=/s/.$/'$FLAG'/i test

2. Redirect the output to a temporary file, then copy the temporary file back on top of the original file.

For option 2 to work, you still need to modify your sed commands. The easiest would be to specify multiple sed commands with the -e option. For instance:
Code:

sed -e '/^\$\$INPUT_FILE_DATE=/s/[0-9]\{6\}/'$DATEMONTH'/' \
    -e '/^\$\$PFFLAG=/s/.$/'$FLAG'/i test > temp_file
mv temp_file test



All times are GMT -5. The time now is 07:55 PM.