Home > Net >  cut command to remove seconds from time. shell scripting
cut command to remove seconds from time. shell scripting

Time:05-24

Lets say we got date and time to a log in the format of

2022-05-18-11:57:140100

I need to remove seconds from this time. It means the final output should be like

 2022-05-18-11:57

I tried the following

echo "2022-05-18-11:57:140100" | rev | cut -d/ -f6- | rev`:"

this was not successful and I have no idea how this cut command works. can anybody explain. Thanks in advance

CodePudding user response:

1st solution: With GNU awk you can simply do it like following. Simple explanation would be, set FS and OFS as : and then in main block of awk program decrease NF with 1 and print the line.

echo "2022-05-18-11:57:140100" | awk 'BEGIN{FS=OFS=":"} NF--'

2nd solution: In any awk using awk's match function please try following.

echo "2022-05-18-11:57:140100" | awk 'match($0,/.*:/){print substr($0,RSTART,RLENGTH-1)}'

3rd solution: Using sed's capability of capturing groups(keep values in temp buffer) please try following code.

echo "2022-05-18-11:57:140100" | sed -E 's/(^[^:]*):([^:]*):.*/\1:\2/'

4th solution(OP's efforts FIX): Fixing OP's efforts using rev cut rev combination here.

echo "2022-05-18-11:57:140100" | rev | cut -d':' -f2- | rev

CodePudding user response:

This can be done easily in bash shell also:

s='2022-05-18-11:57:140100'
echo "${s%:*}"

2022-05-18-11:57

# or else use cut
cut -d: -f1-2 <<< "$s"
2022-05-18-11:57

# or sed
sed 's/:[^:]*$//' <<< "$s"
2022-05-18-11:57

CodePudding user response:

any one of these 5 solutions should work for gawk, mawk-1, mawk-2, and macos nawk :

echo "2022-05-18-11:57:140100" | 

      mawk2   NF=NF   FS=':[^:]*$' OFS=
   or
      gawk -- --NF    FS=':[^:]*$'
   or 
      gawk    NF--    FS=':[^:]*$'
   or
      nawk    NF=1    FS=':[^:]*$'
   or
      mawk  '$!_=$!_' FS=':[^:]*$'

2022-05-18-11:57

The most compacted version would be like

mawk -F':[^:]*$' NF--
  • Related