Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
164 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...