1

In Linux environment, for example I have a file test1 that contains these text:

DB_UP
sqlplus DB_UP test1.sql
DB_UP

I want only to remove the DB_UP beside the sqlplus. How to do it in multiple files with indefinite number of DB_UP before and after the line I really want to edit?

I tried using xarg -i but it also removes the DB_UP that is before and after the sqlplus.

I want the output to be:

DB_UP
sqlplus test1.sql
DB_UP
2
  • Please properly format your input and output as code e.g. using the {} button. Then, please add the exact command you tried (-> xarg -i [sic]).
    – pLumo
    Commented Apr 16, 2021 at 14:32
  • Use sed like this: sed -i.bak 's/sqlplus DB_UP/sqlplus /' FILENAME for a single file. This command generates a backup file named FILENAME.bak which contains the original text. To do this for multiple files, use a loop like for file in f1 f2 f3 f3 f4; do sed -i.bak 's/sqlplus DB_UP/sqlplus /' $file; done. Commented Apr 16, 2021 at 14:49

3 Answers 3

1

The sed substitute command s/DB_UP// will replace the first DB_UP in a line by nothing (in other words, remove it).

Now you only want to do that for lines starting with sqlplus, so use ^sqlplus as an address (condition) for the s command: /^sqlplus/s/DB_UP//. The ^ anchors the pattern to the start of the line.

Check, if your sed version supports the -i option to change the file interactively, then you can loop over the files you want to change and apply the script

sed -i '/^sqlplus/s/DB_UP//' file1 file2 file3

Some sed versions force you to give a file name extension for a backup file after the -i. This may be a good idea if you are worried about messing up things, but you may need to remove the backup files after you made sure everything was fine.

0

Assuming that there is only one DB_UP instance per line, I would use:

sed 's/\(^.*\)\(DB_UP\)\(.*\)$/\1\3/'

If you need to replace all file contents, @berndbausch bash loop would work perfectly:

for file in f1 f2 f3 f3 f4; do
    sed -i.bak 's/\(^.*\)\(DB_UP\)\(.*\)$/\1\3/' "$file"
done
1
  • (1) The \(\) around DB_UP are superfluous, if you don't refer to it later. (2) The ^ anchor is superfluous when starting with .*. (3) Same applies to the $ anchor at the end; the .* will eat everything to the end anyhow. (4) Why include the first and third part of the line anyhow, if you don't use them at all? (5) If there is only one DB_UP per line, your command does the same as s/DB_UP//. (6) This removes all DB_UP in the file, which is not what the OP intended.
    – Philippos
    Commented May 10, 2021 at 10:03
0

With awk:

   awk '/sqlplus\s{1,}DB_UP/{gsub(/sqlplus\s{1,}DB_UP/, "sqlplus");print; next}1' file

This gsub() function replaces DB_UP that comes after sqlplus and whitespace.

This can be shortened to the following command:

awk '{gsub(/sqlplus  *DB_UP/, "sqlplus")}1' file
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .