Saturday, November 13, 2021

[SOLVED] sed move pattern to beginning of line

Issue

I have a textfile with lines of text where I want to move a pattern to the beginning of the line with sed. The pattern is the sequences like [35 of 44].

CSV files and Jupyter _ Even More Python for Beginners - Data Tools [35 of 44].description
Calling An API _ Python for Beginners [36 of 44].description

With \\[.*?\\] I can match this part [11 of 31] of the line, but I can't figure out how to move this pattern to the start of the line.

[35 of 44] CSV files and Jupyter _ Even More Python for Beginners - Data Tools.description
[36 of 44] Calling An API _ Python for Beginners.description

Hopefully, someone can help me!


Solution

With your shown samples, please try following.

awk '
match($0,/\[[^]]*\]/){
  print substr($0,RSTART,RLENGTH),substr($0,1,RSTART-1) substr($0,RSTART+RLENGTH)
}
' Input_file

Explanation: Using match function of awk to match from [ to till ] in each line then printing the matched text's sub string first followed by rest of the line's value.



Answered By - RavinderSingh13