简体   繁体   中英

linux copy files with first row containing genome to other directory

I have many files under the directory. And I want to copy those ones with first line contains "genome" word to a new folder. How should I do that. I can match those line out but I do not know how to manipulate the file again. I build a bash structure like

for i in *
do
  if [ sed -ne 'genome' $i ]
  then cp $i OTHERDIR
  fi
done

But it seems the if statement can do very limited thing and can not have sed in it unlike other programming language.

Try this:

for i in *
do
    head -1 $i| grep "genome" && cp $i OTHERDIR
done

You can use head -1 to peek at the first line:

for i in *
do
  fline=`head -1 $i`
  if [ "$fline" = genome ]
    then cp $i OTHERDIR
  fi
done

First of all, you seem to make no attempt to check only the first line. Your expression should use head to isolate the first line as mentioned by the other posters.

Anyway, you can accomplish this task with sed or grep inside the if statement. The pipe requires the use of output capture $()

With sed: You don't need the -e , it is the default.

$(head -1 $i | sed -n '/genome/=')

With grep: Probably the easier solution. sed is overpowered for this job.

$(head -1 $i | grep genome)

http://www.unix.com/unix-dummies-questions-answers/65705-how-grep-only-1st-line.html

Amazingly I tried the following scripts myself and it works. Haven't check answers posted yet.

for i in *
do
    grep -l "genome" $i | xargs -I one cp one DESTDIR
done

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM