0

I'm using a bash script to read in data from a text file.

#!/bin/bash


file="/home/nexusfactor/Desktop/inputData(linux).txt"
while IFS= read -r line
do
        # display $line or do somthing with $line
    echo "$line"
done <"$file"

Data:

04:31 Alex M.O.R.P.H. & Natalie Gioia - My Heaven http://goo.gl/rMOa2q
[ARMADA MUSIC]

07:46 Fabio XB & Liuck feat. Christina Novelli - Back To You (Wach Remix) http://goo.gl/yGxqRX
[DIGITAL SOCIETY RECORDINGS]

I would like to remove the white space between the two songs, then remove the time at the beginning of the song and the hyperlink/studio name from the end of the file. So my output would be:

Alex M.O.R.P.H. & Natalie Gioia - My Heaven
Fabio XB & Liuck feat. Christina Novelli
1

You can use grep in Perl-mode to use lookbehinds and lookaheads to extract the relevant parts (between the timecode and the link at the end. It needs to match the format or it won't parse the line, so that sorts out your whitespace issue too.

$ grep -Po '(?<=\d\d:\d\d ).*(?= http)' data
Alex M.O.R.P.H. & Natalie Gioia - My Heaven
Fabio XB & Liuck feat. Christina Novelli - Back To You (Wach Remix)

And grep can handle STDIN if you need to loop it:

while read line
do
    echo "$line" | grep -Po '(?<=\d\d:\d\d ).*(?= http)'
done < /home/oli/Desktop/data

Though if you're only interested in the filtered data, I'd loop the output of grep:

grep -Po '(?<=\d\d:\d\d ).*(?= http)' data | \
while read line
do
    echo "$line"
done
  • Thanks, if you could, I'll update my code, I'm reading the data from a text file. Could you show me how to edit it in a loop? – user368055 Jan 15 '15 at 17:31
  • Is it possible to use sed and awk? – user368055 Jan 15 '15 at 17:33
  • You can use whatever you like —sed, perl, awk should all work— but I've used grep. I've added some bash-looped versions. – Oli Jan 15 '15 at 17:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy