Showing posts with label shell. Show all posts
Showing posts with label shell. Show all posts

Tuesday, July 28, 2020

How to cat multiline content into a file with shell

Sometimes we want to copy a paragraph then paste into or append into a file.
We can use a text editor, such as vi to do the copy paste.

It will be convenient to do it in command line with just cat and >.

Here is the example, the normal way is echo some thing followed by >. 
In case of multi-line, we need to use <<EOF to mark the end of the file.
EOF won't be a literal string that enters the final result, it is the marker of End Of File instead.

here is the example code:

demo>cat > demo.txt <<EOF
> adfd
> dfadfad
> adfafa
> EOF
demo>cat demo.txt
adfd
dfadfad
adfafa
demo>

The file content is now get updated with your strings.


Thursday, May 21, 2020

How to generate date string with shell command

Sometimes we need to generate date string, the shell command default format can brings us somewhere, but how about the date with format 20-05-10?
We can print date string using shell command date with format flags.

date +%y-%m-%d
for example will print today's date in short format as
20-05-13

sometimes, the generate date strings can be used to construct other shell commands with ``.
The date command wrapping inside `` will get executed first, the result string then concatenated with the rest of the strings to form a shell command.

For example, when the following command is executed

echo filename.`date +%y-%m-%d`.log

`date +%y-%m-%d` will execute first, generate a string 20-05-13. Then string 20-05-13 is concatenated with rest of the command to get a new shell command:

echo filename.20-05-13.log

the above command's running result is
filename.20-05-13.log
 
=================
demo>date
Wed May 13 15:05:10 EDT 2020
demo>date +%y-%m-%d
20-05-13
demo>echo filename.`date +%y-%m-%d`.log
filename.20-05-13.log
==================

Similarly, we can use the same technique to construct more sophisticated grep shell command:

ls myapp.`date +%y-%m-%d`*.log | xargs -I {} cat{} | grep -i 'exception\|error' -A 2 -B 2

the above command, list all myapp log files generated today. Among though files, we search for exception and error messages, print out the line with 2 lines before and 2 lines after.

Tuesday, May 12, 2020

How to create a new file in shell script with cat EOF

demo>cat test.sh
#!/bin/bash
rm -f temp_config

cat > temp_config <<-EOF
sfdfadfadfadf
dfadfadfad
[xxxx]
xfdfdf
EOF

cat temp_config
ls -lrt temp_config
demo>
demo>./test.sh
sfdfadfadfadf
dfadfadfad
[xxxx]
xfdfdf
-rw-r--r--  1 homenetwork  staff  39 May 12 14:52 temp_config
demo>

MarketAxess

MarketAxess: The Leader in e-Trading for Global Fixed Income MarketAxess Holdings Inc. (MarketAxess) is an international financial technol...