1

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
jorginho97
  • 43
  • 6
  • Hello @george123. Welcome to SO. Have you made some reasearches yet? Could you please show us what you have already tried? Also consider reading this: https://stackoverflow.com/help/how-to-ask – Maël Pedretti Sep 19 '18 at 09:34
  • Try `sed -i 's/^SF://'` (or, `sed -i '' 's/^SF://'` if you are on Mac) if all you want is to remove `SF:` at the start of each line – Wiktor Stribiżew Sep 19 '18 at 09:34
  • make a small example, what you have, and what do you want to get. we don't know what text in your `$LINE` – Kent Sep 19 '18 at 09:53
  • 1
    I went looking for a solution for exactly the same problem, and I do mean exactly. I assume you're doing this because the SonarTS plugin in SonarQube doesn't handle symlinks? – David M. Karr Dec 15 '20 at 16:46
  • No, it was related to the LCOV code coverage tool, but this tool doesn't handle symlinks too. – jorginho97 Dec 16 '20 at 17:21

1 Answers1

3

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
glenn jackman
  • 238,783
  • 38
  • 220
  • 352