Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
182 views
in Technique[技术] by (71.8m points)

linux - grep the lines of file using for loop

There is a file and each line shows the different file paths.

    ```
      my_file
      /the/first/path/file1
      /the/second/path/file2
      ....
    ```

I want to use for loop to find a string in each file.

     ```
      for i in $(cat my_file); do cd "$i"; done | grep -w string "$i"

     ```

But this seems not working for me. I am getting this for all file directory

    -bash: cd: /the/first/path/file1: No such file or directory

What am I doing wrong? Thanks in advance for any help

question from:https://stackoverflow.com/questions/66056508/grep-the-lines-of-file-using-for-loop

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

No need for a for loop, use xargs:

xargs -a my_file -d '
' grep -h -w string

Note #1: I added the -h option (GNU extension) so that the filenames are not added by grep in the output (like in your command).

Note #2: since you are using Linux and Bash, I'm assuming GNU xargs. If your xargs does not understand the -a option, then use this instead:

< my_file xargs -d '
' grep -h -w string

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...