LoginSignup
0

More than 5 years have passed since last update.

bash > 文字列処理 > replace_first_N_chars_180618_exec v0.1 > 一行の先頭文字列を別の文字列で書替える

Posted at
動作環境
Xeon E5-2620 v4 (8コア) x 2
32GB RAM
GeForce GT 730 1GB GDDR5
CentOS 6.9 (64bit)
NCAR Command Language Version 6.3.0
for WRF3.7.1, WPS3.7.1
  openmpi-1.8.x86_64 とその-devel
  mpich.x86_64 3.1-5.el6とその-devel
  gcc version 4.4.7 (とgfortran)
for WRF3.9, WPS3.9
  Open MPI v2.1.1
  gcc version 4.9.2 (とgfortran; devtoolset-3使用)
 NetCDF v4.4.1.1, NetCDF (Fortran API) v4.4.4
Python 2.6.6 (r266:84292, Aug 18 2016, 15:13:37) 
Python 3.6.0 on virtualenv
GNU bash, version 4.1.2(2)-release (x86_64-redhat-linux-gnu)
date (GNU coreutils) 8.4 
tmux 1.6-3.el6

処理概要

  • 20180612 120000 beginning of the processという文字列の先頭文字列を任意の文字列で置換える

参考

@tukiyo3 さんに教えていただいたcutを使います。

code v0.1

replace_first_N_chars_180618_exec
#!/usr/bin/env bash

set -eu #just in case

# v0.1 Jun. 18, 2018
#   - replace first 15 chars
#

function replace_datetime () {
    # [cmd] [INTXT] [TOTXT]
    # e.g. [cmd] "20180612 120000 ..." "20180618 230000"

    echo "$2"$(echo $1 | cut -b "16-")  
}

# original text
#      1234567890123456
INTXT="20180612 120000 beginning of the process"
# new date and time
TOTXT="20180618 230000"

# example
echo $INTXT
res=$(replace_datetime "$INTXT" "$TOTXT")
echo $res

実行

$ bash replace_first_N_chars_180618_exec 
20180612 120000 beginning of the process
20180618 230000 beginning of the process

注意点

文字列の中に空白を含めるためreplace_datetime 使用時は二重引用符で囲うこと。

備考

先頭のN文字列のNは固定にしている。

今は可変である必要がないため。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0