Hi,
Need a help with shell script. I have to search for a string in one of the file, if match found, copy the line to a new file and delete the line from the exisiting file.
eg:
if 835100000000000638 is found, i need to replace it with 835100000000000639 and write to a new file. Also I need the 835100000000000638 to be deleted from my exising file.
I tried
sed -n "s/835100000000000638/835100000000000639/p oldfile > newfile
this will find and write to new file but wont delete from existing file.
# strip lines out of file and make new file of lines removed and modified
# set up patterns - any regex will work
BEGIN {
MY_PAT="835100000000000638"
NEW_PAT="835100000000000639"
}
# This clause is executed on the opening of each file on the command line
# It first checks to see if this is not the first file and cleans up the
# previous files and copies the new stripped file to the old file
# NOTE: I would prefer if it didn't overwrite the input file...
# It then creates the names and commands it will need later
(FNR == 1) { # check if first line of new file
if ( NR != 1) # see if this is not first file
{
close(FILEOUT) # if true, then we close previous files
close(FILELOG)
system(FILECP) # do the copy
system(FILERM) # remove the work file
}
FILEOUT = FILENAME ".strip" # create striped file name using input file name
FILELOG = FILENAME ".new" # create new file
FILECP = "cp " FILEOUT " " FILENAME # copy command
FILERM = "rm " FILEOUT # remove strip file
}
# This clause executes for every line
# It copies lines from the input file to the appropriate output file
{
if ( sub(MY_PAT,NEW_PAT) == 0 ) # test for pattern in line
print > FILEOUT # save to stripped file if pattern not found
else
print > FILELOG # save to remove log if pattern match
}
# This clause is executed when the last line of the last file is reached
END {
system(FILECP) # clean up last file
system(FILERM)
}
Then execute:
awk -f strip.awk <data.file>
It will create a file with .new with the removed lines....