简体   繁体   中英

sed for specific line which contains a string

I have a file such as

READS2b=/path1/path2/data/a_ACTTGA_L002_R2.fastq.gz.1
READS2b=/path1/path2/data/a_ACTTGA_L004_R2.fastq.gz.1
READS2b=/path1/path2/data/a_ACTTGA_L004_R2.fastq.gz

and I would like to change /path1/path2/data/ to /path4/path5/data/ only for line which contains .fastq.gz.1 .

Here I should get:

READS2b=/path4/path5/data/a_ACTTGA_L002_R2.fastq.gz.1
READS2b=/path4/path5/data/a_ACTTGA_L004_R2.fastq.gz.1
READS2b=/path1/path2/data/a_ACTTGA_L004_R2.fastq.gz

I would use:

sed 's@/path1/path2/@path4/path5/@g' file.txt

but I do not know how to do it only for line with .fastq.gz.1

You can use

sed '/\.fastq\.gz\.1$/s@/path1/path2/data/@path4/path5/data/@g' file.txt

See a sed demo

Here,

  • /\.fastq\.gz\.1$/ finds lines that end with .fastq.gz.1
  • s@/path1/path2/data@path4/path5/data/@g only replaces /path1/path2/data/ with path4/path5/data/ on those lines.

This might work for you (GNU sed):

sed '/\.fastq\.gz\.1/s#/path1/path2\(/data/\)/path4/path5\1#' file

Focus on lines that contain .fastq.gz.1 and substitute when patterns match.

Could you please try following, in case you are ok with awk . In awk solution I have come up with 2 variables named currText and newText which are self explantory by their name itself, one could place text in these variables and we could globally substitute currText value with newText in lines wherever lines have .fastq.gz.1 in it.

awk -v currText="/path1/path2/data/" -v newText="/path4/path5/data/" '
/\.fastq\.gz\.1/{
  gsub(currText,newText)
}
1
' Input_file

Using GNU awk :

awk '/fastq.gz.1/ {gsub(/path1/,"path4") gsub(/path2/, "path5")}'1 file
READS2b=/path4/path5/data/a_ACTTGA_L002_R2.fastq.gz.1
READS2b=/path4/path5/data/a_ACTTGA_L004_R2.fastq.gz.1
READS2b=/path1/path2/data/a_ACTTGA_L004_R2.fastq.gz

this code:

  • first the condition. Only these records: /fastq.gz.1/ , not all.
  • and second the action, in this case the substitutions with gsub .

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