Linux - Edit multiple files using another file as source

Asked

Viewed 102 times

1

I have a file (list name.txt) with several names, one per line.

I need to edit or remove all the names that are on listanome.txt of several other files

With I think which files should be dictated, but there are many.

grep -Ff listanome.txt /caminho

I’m having trouble using the or using as a basis a file.

3 answers

2


Use your index file listanome.txt to make a script to be used by sed to remove the lines:

To a listanome.txt as below...

$ cat listanome.txt 
ze
jao
juca

...the following sed turns into an delete script for each name in the list:

$ sed 's/^/\//; s/$/\/d/' listanome.txt
/ze/d
/jao/d
/juca/d

So, pass such a command sed to the flag -f of a new sed, which will execute such a script on all files to be affected, supposedly contained in the directory caminho:

$ sed --in-place=.bak -f <(sed 's/^/\//; s/$/\/d/' listanome.txt) /caminho/*

This will delete all lines from all files in the directory caminho containing the names of listanome.txt, backing up with the extension ". Bak" for each changed file.

If your requirement changes, change the first sed according to what you want, for example:

  • To delete all lines identical to the index:

    $ sed 's/^/\/^/; s/$/$\/d/' listanome.txt
    /^ze$/d
    /^jao$/d
    /^juca$/d
    
  • To replace the line contents with the string "REMOVE":

    $ sed 's/^/\/^\.\*/; s/$/\.\*$\/REMOVER\/g/' listanome.txt
    /^.*ze.*$/REMOVER/g
    /^.*jao.*$/REMOVER/g
    /^.*juca.*$/REMOVER/g
    
  • I think this one can work!! Great, let me play and return here :)

  • It worked perfectly, you rock! VLW!

0

You can use the xargs to accomplish the desired task, follows below an example where I list a directory and get all the files . cfg and insert a line into the found files.:

ls *.cfg | xargs sed -i"23i#####################################################"

better understanding the above command:

ls *.cfg -> lists all files ending with the extension .cfg

| xargs -> takes the data that was displayed in the previous command to apply the next command.

sed -i"23i#####################################################" -> inserts a line into each file found in the command ls, in this case I am inserting on line 23 of each file.

I believe that in your need the ideal would be to create a for that reads each line of your first file and after that apply the necessary action.

  • Thank you very much. Unfortunately I couldn’t make it work that way because I need to edit the line containing the name, or remove the line with the name. I have no way of knowing in which line the names will be, for example. I think I will have q use some script same =/

  • with grep -n you can know the line you are looking for, so you can pass the line as parameter

0

Using Awk tries to:

awk 'NR==FNR {c[$0]++} !c[$0]'  listanome.txt outro

Browser other questions tagged

You are not signed in. Login or sign up in order to post.