1

Need to remove .sql entry in file

I have file which contains strings ends with both .class and .sql and I need to remove only string which ends with .sql in the file

file.txt

actual.class
actual1.class
actual2.class
actual3.class
actual4.class
test.sql
test2.sql
test3.sql
test4.sql
test5.sql

Output file which i expect is

actual.class
actual1.class
actual2.class
actual3.class
actual4.class

Using below script but not able to achieve

for i in `cat file.txt` ; do
    fname=`echo ${i} | cut -d "." -f1`
    echo ${fname}
    if file=${fname}.sql
    then
    sed "/${fname}.sql/d" file.txt > output_file.txt
    else
    exit 0
    fi
done

with above script getting below output

actual.class
actual1.class
actual2.class
actual3.class
actual4.class
test.sql
test2.sql
test3.sql

4 Answers 4

2

grep solution:

grep -q '.\.sql$' file.txt && grep -v '\.sql$' file.txt > output_file.txt

The 2nd grep statement/command will be executed only if the 1st one returned zero exit status 0 if any match against pattern .\.sql$ is found


The final output_file.txt content:

actual.class
actual1.class
actual2.class
actual3.class
actual4.class
1
  • Using sed

    sed '/\.sql$/d' test.txt
    
  • For bash (3.2+)

    while read -r line; do [[ ! $line =~ .sql ]] && echo "$line"; done <test.txt
    
  • Using perl

    perl -ni.bak -e "print unless /.sql/" test.txt
    
1
  • 1
    Anchoring the pattern to $ end-of-line would be an improvement Commented Dec 6, 2017 at 11:10
0

Another grep, just invert the match

grep -v "\.sql$" filelist
0

I think there are already good solutions before this post. However I would like to point out several issues with the script originally posted.

  • for i in $(cat ...) is not good as it seperates your input by spaces by default as well, not just by newline.
  • The if statement doesn't make sense as file is not defined. For a typical if statement you would need to invoke test, usually by putting things inside a pair of square brackets. For example, if [ $f = "abc" ]; then. Note that all spaces here are necessary.
  • exit 0 stops the script from handling all the lines after the given line, I believe that is not intended.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.