2

I have a file "list" as following:

main.c getname 25
main.c getage  36
util.c namecheck 123

The above has first string file name, second function name, and third line no. I want to:

  1. Open the file(1st column)
  2. Go to line no (3rd column)
  3. Edit the string (2nd column).

Ex: Open the file main.c, change the string getname to getname() in line no 25

Does anyone know how to do the above using sed and awk?

I tried to use the following. But it doesn't work

awk '{ sed -e "$3s/$2/&()" <$1 >$1_new }' list
1

If you don't want to change the original files, you have to iterate over the filenames in list and copy them away, since otherwise redirection > would overwrite any previous change to the new file (which happens if you have several entries for the same file in list). Something along the lines of this would leave your originals untouched:

#!/bin/bash

list=testlist.txt

# get the first column in $list, sort it, remove duplicates
# and copy file to *_new. ignore if it doesn't exist
awk '{ print $1 }' "${list}" | sort -u | while read file; do
    [ -e "${file}" ] || continue
    cp "${file}" "${file}_new"
done

# for each line in $list, get the filename, function name and line number
while read file func lineno; do
    # change filename to the one we wish to apply the changes to
    file="${file}_new"

    # file should exist as we just created it,
    # but if it doesn't, skip entry.
    [ -e "${file}" ] || continue

    # replace
    sed -i "${lineno}s/${func}/${func}()/" "${file}"
done < "${list}"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.