# [Record] String processing in Shell and Makefile ###### tags: `sed`, `grep`, `tr`, `cut` [toc] ## Introduction String processing is a common work in a system program. Sometimes, we need to find a string and compare it with others. In this note, I will share some useful usage of tools like grep, sed, tr and cut and so on. And these tools can be used in a shell or Makefile. ## Shell - Extract the value of a matched pattern in a line For example, in .config file with a line and we want to get 0.0.30 - Input ``` MY_VERSION="0.0.30" ``` - Action to get the version number ``` VERSION=$(sed -n 's/^MY_VERSION=//p' .config | tr -d '"') ``` - Output ``` VERSION=0.0.30 ``` :::info - s/regex/ is the framework - /p means to print - ^ means starting with - tr -d means to delete the symbol ::: - Get the substring - Input ``` MY_PATH="/home/user/download/crazyfox_1.0.1/resource/123.jpg" ``` - Action to get the string **crazyfox_1.0.1** ``` APPNAME=$(sed -n 's/^MY_PATH=//p' .config | tr -d '"'| cut -d'/' -f4) ``` - Output ``` APPNAME=crazyfox_1.0.1 ``` :::info - cut -d'/' means to cut the symbol - -f4 means to pull out the fields of interest. ::: - Get the datetime by finding an epoch in a log file and convert it - Input ``` 1593875589.241796866:end :build : linux ``` - Action ```shell MY_EPOCH=$(date -d @$(grep -r ":end :build : linux" output/build/build-time.log | tail -1 | cut -d'.' -f1) +'%Y/%m/%d %H:%M:%S') ``` - Output ``` MY_EPOCH=2020/07/04 23:13:09 ``` :::info - date -d @ +"..." means to convert the epoch to a formatted datetime - grep -r string file means to find strings in a file ::: - To check if a strings is in a file - Action ``` if grep -Eq "^ENABLE_SSH=y$" .config; then echo enable ssh else echo disable ssh ``` - To compare two strings - Action ```shell if [[ -z "$(fw_printenv | grep "bootargs")" ]] then echo cannot get bootargs elif [ "$(fw_printenv | grep "bootargs")" = "bootargs root=/dev/nfs" ] echo get bootargs ``` ## Reference https://superuser.com/questions/461946/can-i-use-pipe-output-as-a-shell-script-argument http://puremonkey2010.blogspot.com/2015/11/linux-tr_28.html https://shapeshed.com/unix-cut/