jorginho97
jorginho97

Reputation: 43

Change path using awk or sed

Hello i want to change symlink path to real path in txt file. First I find word "SF:" and change path. Now i use this script but it is slow and not effective. I think it can be changed by awk or sed command. Thank you in advance.

#!/bin/bash
FILENAME="new1.info"
    echo "" > $FILENAME
while read LINE
do
if [ "" != "$(echo $LINE | grep -e "^SF:")" ]
then
    echo "SF:""$(realpath $(echo $LINE | cut -d":" -f2))" >> $FILENAME
else
    echo $LINE >> $FILENAME
fi
done < total.info

I have big txt file, so I want to find "SF:" and change line from something like this:

SF:/home/ects/svn/moduleTests/ctest/tests/moduletests/base/tmp/src/base64.cpp

To this:

SF:/home/ects/svn/moduleTests/ctest/src/base/base64.cpp

Upvotes: 1

Views: 584

Answers (1)

glenn jackman
glenn jackman

Reputation: 246807

In bash, I'd write

#!/bin/bash
while IFS= read -r line; do
    if [[ "$line" == "SF:"* ]]; then
        line="SF:$(realpath "${line#SF:}")"
    fi
    echo "$line"
done < total.info > new1.info

Things to note:

  • quote your variables, every time.
  • don't use ALLCAPS varnames, it will bite you eventually
  • note the output redirection has been moved to the outside of the while loop, just like the input redirection
  • IFS= read -r line is the way to read lines from the file exactly.

I don't know if this will be any faster: bash can be quite slow, particular for while read loops over big files. You could try another language:

perl -MCwd=abs_path -pe 's/^SF:\K(.*)/ abs_path($1) /e' total.info > new1.info

Upvotes: 3

Related Questions