Click here to Skip to main content
15,067,649 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm trying to remove the HH:MM:SS section in the following string example:

Mar 6 01:00:53 2026

The problem is that I cannot go by character position because the text length can change. Example, there could be 16th instead of 6. Therefore I need a way to look for characters immediately before and after the ":" and remove them.

The output should look like this:

Mar 6 2026

What I have tried:

(date1 derived from a previous operation)

echo $date1
Mar 6 01:00:53 2026

date2=`cut -c 7-15 <<< $date1`

echo $date2 
01:00:53 #< -- I was expecting this to be the date minus the HH:MM:SS, but this is the wrong approach anyway because of the variable length.
Posted
Updated 13-Oct-21 12:42pm

date2=$(echo $date1 | awk '{print $1 " " $2 " " $4}')
   
Comments
wifinut 13-Oct-21 21:26pm
   
Thanks so much. This gives me exactly what I need.
You're really close:
Shell
date2=$(echo $date1 | cut -f3 -d\ )
should do the trick. In this case we're telling cut to return the 3rd field (-f3 flag), with field separator space, (-d\ flag ). Note that for the -d flag you need to make the space char significant using the backslash, otherwise the shell will treat the space a an argument separator, and will complain that option -d requires an argument.
I prefer the $( ... ) form of command substitution, since it can be nested e.g. cmd1 $(cmd2 $(cmd3 arg-a arg-b) arg-3 arg-4) arg-x does what you expect: it executes cmd3 and uses the results of that as an argument to cmd2, the output of which is then passed in as an argument to cmd1.
If you know the column positions, you can save a some overhead using the ${parameter:offset:length} Parameter substitution. In you example above echo ${date1:7:7} does what you want, as long as its the first 9 days of the month, which I think is what you were referring to as the "wrong approach". Bash provides several conversions like this, Look at the man page for bash and search for "Parameter Expansion" to find what is available.
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900