1

I have a csv file that has many lines of timestamps in following format HH:MM:SS:MS
For example:

00.00.07.38    
00.00.08.13    
00.00.08.88

The hour is not relevant to me so I would like to cut it out. How do I remove HH from every line in file with bash.

I can read line by line from the file

while IFS=, read col1
do
    #remove HH from every line
    #awk -F '[.]' '{print $1}' <<< $col1 #only prints one portion of time
    #echo $col1 | cut -d"." -f2 | cut -d"." -f3 | cut -d"." -f4
done < $file

I have been playing around with awk and cut but was only able to print a specific position ex HH etc

But how to remove just the HH from the line without creating a new file?

Sundeep
  • 12,008
S4M11R
  • 113
  • I could use following to remove HH sed 's/^.{3}//g' logfile but then I would need to create a new file to store values. I would like to just remove HH and keep same file if possible – S4M11R Nov 14 '16 at 14:09

4 Answers4

0

Just use sed:

sed -i.bak 's/[0-9]\{2\}.//' myfile

This will remove the two starting digits when followed by a period, and replace your file, saving the original as a backup (myfile.bak).

0

Maybe not the best solution but it works

I just create a tempfile that I later rename to original file name.

function fixTime() {
  file="zipstream_test/timeLog.csv"
  tmpFile="zipstream_test/timeTmp.csv"
  #Remove HH from file, ie remove first 3 chars
  sed 's/^.\{3\}//g' $file > $tmpFile
  rm $file
  mv $tmpFile $file
}

fixTime
S4M11R
  • 113
  • Note that sed already contains a built in backup option. see my answer. – Nathaniel Bubis Nov 14 '16 at 14:15
  • g flag is unnecessary... see also: https://unix.stackexchange.com/questions/95884/how-can-i-get-my-sed-command-to-make-permanent-changes-to-a-file and https://unix.stackexchange.com/questions/92895/how-to-achieve-portability-with-sed-i-in-place-editing – Sundeep Nov 14 '16 at 14:19
0

You were almost there with your script:

file=filename

while    IFS=. read h m s n
do       echo "$m.$s.$n"
done     < "$file"

The use of IFS as a dot (.) allows read to split the input (< "$file") in parts. The parts get assigned to h, m, s and n. Then we just print the parts that re needed. In fact, an easier solution will be:

file=filename

while    IFS=. read h m
do       echo "$m"
done     < "$file"

The variable h takes the first part, the variable m takes the rest, then just print it.

0

Since was one of the tags:

$ cut -d . -f 2- file
00.07.38
00.08.13
00.08.88

This makes cut threat the file as a dot-delimited set of fields. It extracts all fields from field 2 onwards for each line.

Kusalananda
  • 333,661