如何对file1.txt的stat结果中提取的Modify行执行插入操作?
stat Hey there! Let's walk through practical, command-line friendly ways to perform insertion operations on that Modify line you pulled from stat. These tools are go-tos for quick text manipulation tasks like this:
Using sed for Pattern-Based Insertion
sed excels at targeted text changes where you want to insert content at a specific pattern. Here are two common use cases:
Insert text right after the "Modify:" label
# First capture the Modify line modify_line=$(stat file1.txt | grep Modify) # Insert custom text immediately after the label echo "$modify_line" | sed 's/Modify: /Modify: [Edited] /'Output:
Modify: [Edited] 2018-04-19 19:18:58.216117199 +0200Insert text between the date and time
Use a capture group to target the date string, then append your text before moving to the time segment:echo "$modify_line" | sed 's/\(2018-04-19\)/\1 [Last Edited On] /'Output:
Modify: 2018-04-19 [Last Edited On] 19:18:58.216117199 +0200
Using awk for Field-Based Insertion
Since the Modify line is structured with whitespace-separated fields, awk lets you insert text by targeting specific fields directly:
- Insert after the "Modify:" label (field 1)
echo "$modify_line" | awk '{print $1, "[Custom Tag]", $2, $3, $4}' - Insert between the date (field 2) and time (field 3)
echo "$modify_line" | awk '{print $1, $2, "[Inserted Here]", $3, $4}'
Using String Slicing with cut
If you prefer splitting the line into explicit parts and manually combining them:
# Extract the prefix (Modify: + date) prefix=$(echo "$modify_line" | cut -d' ' -f1-2) # Extract the suffix (time + timezone) suffix=$(echo "$modify_line" | cut -d' ' -f3-) # Combine all parts with your inserted text echo "$prefix [My Inserted Content] $suffix"
Saving the Modified Output
If you want to update the full stat output with your modified line and save it to a file:
stat file1.txt | sed '/Modify:/s/Modify: /Modify: [Updated Timestamp] /' > updated_stat.txt
内容的提问来源于stack exchange,提问作者marc

