вычесть и заменить значения в строке с помощью оболочки

В таких случаях я предпочитаю perl -pi.bak.

FMTYEWTK на http://www.perl.com/pub/2004/10/14/file_editing.html

(FMTYEWTK означает «гораздо больше, чем вы когда-либо хотели знать»)

1
09.02.2019, 10:48
4 ответа

Вы можете заменить весь цикл whileэтой строкой:

awk -F'[._]' '{print $2"-"$3"-"$4"-"$5$6$7}' $path/all_files.txt

Если вы хотите сохранить расширение файлов (.txt), вы должны использовать такую ​​команду:

awk -F_ '{print $2"-"$3"-"$4"-"$5$6$7}' $path/all_files.txt
2
27.01.2020, 23:31
#!/bin/sh

# Given arguments:
#    A single directory path to somewhere that has *.txt files.
# Assumption:
#    All *.txt files have filenames on the format XXXX_YYYY_MM_DD_hh_mm_ss.txt.
# Output:
#    The YYYY_MM_DD_hh_mm_ss part of each filename on the format YYYY-MM-DD-hhmmss.

# Set the positional parameters to the list of pathnames in the given directory.
set -- "$1"/*.txt

# Turn off filename globbing and set field splitting delimiter to an underscore.
set -f
IFS='_'

# Loop over the positional parameters generated above.
for pathname do
    # If this is not a regular file (or a symbolic link to one), skip.
    [ ! -f "$pathname" ] && continue

    # Get the filename portion of the pathname and delete the filename suffix.
    filename=$( basename "$pathname".txt )

    # Delete the bit up to the first underscore in the remaining string.
    filename=${filename#*_}

    # Rely on the shell's word splitting to split the sting up into
    # separate words and then use printf to assemble the words inte the
    # format that we want.
    printf '%s-%s-%s-%s%s%s\n' $filename
done

Тестирование:

$ ls dir
1232_2019_02_09_12_29_29.txt  1232_2019_02_09_12_29_55.txt
$ sh script.sh dir
2019-02-09-122929
2019-02-09-122955

Похожие:

0
27.01.2020, 23:31

Я использовал описанный ниже метод для достижения того же

awk -F "_" 'OFS="-"{$1="";print $0}' filename|sed "s/\..*//g"| sed 's/^-//g'| awk '{print substr($1,1,13)substr($1,15,2)substr($1,18)}'

выход

2019-02-09-122929
2019-02-09-122955
0
27.01.2020, 23:31

Использованиеsed:

sed 's/^[^_]*_\(.*\)\..*$/\1/;y/_/-/;s/-\([^-]*\)-\([^-]*\)$/\1\2/' \
     $path/all_files.txt 
0
27.01.2020, 23:31

Теги

Похожие вопросы